package com.starrin.tennisfinder.scheduler;

import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.starrin.tennisfinder.extractors.AvailabilityExtractorCommodus;
import com.starrin.tennisfinder.model.VenueAvailabilityDataHolder;
import com.starrin.tennisfinder.system.Cache;
import com.starrin.tennisfinder.util.WebUtil;
import org.apache.log4j.Logger;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by larsstarrin on 06/02/14.
 */
public class RefreshTaskCommodus implements Runnable {

    private Map<String, VenueAvailabilityDataHolder> newData = new HashMap<>();
    private Cache cache = Cache.getInstance();
    private static final Logger logger = Logger.getLogger(RefreshTaskCommodus.class);
    private static final int FORESIGHT_DAYS = 15;
    private String venueKey;
    private String clubId;
    private String itemsIndoors;
    private String itemsOutdoors;

    public RefreshTaskCommodus(String venueKey, String clubId, String itemsIndoors, String itemsOutdoors) {
        this.venueKey = venueKey;
        this.clubId = clubId;
        this.itemsIndoors = itemsIndoors;
        this.itemsOutdoors = itemsOutdoors;
    }

    public void run() {
        logger.info("Start refreshing availability data for " + venueKey);
        long start = System.currentTimeMillis();
        try {
            refresh("http://www.commodusnet.net/kund/adminschedule.php?sess_adm_club_id=%s&YEAR=%s&MONTH=%s&DAY=%s", clubId);

            //Put temp data into cache
            for (Map.Entry<String, VenueAvailabilityDataHolder> entry : newData.entrySet()) {
                cache.putEntry(entry.getKey(), venueKey, entry.getValue());
            }
            logger.info("Finished refreshing availability data for " + venueKey + " in " +  (System.currentTimeMillis() - start) / 1000 + " seconds");

        } catch (Exception e) {
            logger.error("Error fetching data for " + venueKey, e);
        }
    }

    private void refresh(String urlTemplate, String clubId) throws Exception {
        for (int i = 0; i < FORESIGHT_DAYS; i++) {
            Calendar cal = new GregorianCalendar();
            cal.add(Calendar.DAY_OF_MONTH, i);
            SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
            String dateString = df.format(cal.getTime());

            String year = dateString.substring(0, 4);
            String month = dateString.substring(4, 6);
            String day = dateString.substring(6, 8);

            String url = String.format(urlTemplate, clubId, year, month, day);

            WebClient webClient = new WebClient();
            webClient.getOptions().setThrowExceptionOnScriptError(false);
            webClient.getOptions().setJavaScriptEnabled(false);
            try {
                HtmlPage page = webClient.getPage(url);
                String response = WebUtil.getReducedResponse(page.getWebResponse().getContentAsString(), "07:00-08:00");
                VenueAvailabilityDataHolder dataHolder = new AvailabilityExtractorCommodus().extractVenueAvailability(response, url, itemsIndoors, itemsOutdoors);
                newData.put(dateString, dataHolder);
            } catch(IOException e) {
               logger.error("Error when fetching data for venue: " + venueKey + " url: "+ url + " cause:" + e.getLocalizedMessage());
            }
        }
    }

}
